<template>
  <div class="main">
    <!--面包屑-->
    <div class="top">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>项目群</el-breadcrumb-item>
        <el-breadcrumb-item>工单/报警</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/worderList' }"
          >工单列表</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>

    <div>
      <el-card class="card">
        <!--标题文字-->
        <div class="headerTitle">
          <div>工单列表</div>
        </div>
        <!-- 统计 -->
        <!--搜索输入框-->
        <div class="search">
          <div style="width: 1000px; margin-left: 20px; display: flex">
            <p class="itemsli">
              <span>未读：</span>
              <span class="lis">{{ counts.data.wd }}</span>
            </p>
            <p class="itemsli">
              <span>已阅：</span>
              <span class="lis">{{ counts.data.yd }}</span>
            </p>
            <p class="itemsli">
              <span>成功执行：</span>
              <span class="lis">{{ counts.data.cg }}</span>
            </p>
            <p class="itemsli">
              <span>因故不执行：</span>
              <span class="lis">{{ counts.data.yg }}</span>
            </p>
            <p class="itemsli">
              <span>无理由不执行（超出时间）：</span>
              <span class="lis">{{ counts.data.wly }}</span>
            </p>
          </div>
          <el-select
            v-model="value"
            placeholder="能效"
            size="default"
            style="width: 150px; margin-left: 70px"
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <el-select
            v-model="value1"
            placeholder="一小时"
            size="default"
            style="width: 150px; margin-left: 10px"
          >
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <el-date-picker
            :disabled-date="disabledDate"
            v-model="value2"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 300px; margin-left: 10px"
            @change="dateCreateTimeHandle"
          />

          <el-button class="btn" @click="exportExcel">下载</el-button>

          <!-- <el-button class='btn'>打印</el-button> -->
        </div>

        <!--表格内容-->
        <div style="padding: 0 20px">
          <el-table
            id="table"
            :data="tt"
            border
            style="width: 100%"
            height="600px"
            :header-cell-style="{
              'text-align': 'center',
              background: '#B4C7E7',
              color: '#333333',
            }"
            :header-cell-class-name="cellClass"
            :row-class-name="tableRowClassName"
          >
            <el-table-column type="selection" width="50px" align="center" />

            <el-table-column label="工单发出" align="center" width="100px">
              <template #default="scope">
                <p>
                  {{
                    dayjs(scope.row.createTime || "1").format(
                      "YYYY-MM-DD HH:mm:ss"
                    )
                  }}
                </p>
              </template>
            </el-table-column>
            <el-table-column label="预期完成" align="center" width="100px">
              <template #default="scope">
                <p>
                  {{
                    dayjs(scope.row.expectedCompletionTime || "1").format(
                      "YYYY-MM-DD HH:mm:ss"
                    )
                  }}
                </p>
              </template>
            </el-table-column>
            <el-table-column label="实际完成" align="center" width="95px">
              <template #default="scope">
                <p>
                  {{ scope.row.actualFinishTime || " " }}
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="faultRecoveryTime"
              label="故障修复"
              align="center"
              width="100px"
            >
              <!-- <template #default="scope">
                <p>
                  {{
                    dayjs(scope.row.faultRecoveryTime || "1").format(
                      "YYYY-MM-DD HH:mm:ss"
                    )
                  }}
                </p>
              </template> -->
            </el-table-column>

            <el-table-column label="响应" width="100px" align="center">
              <template #default="scope">
                <p>
                  {{ scope.row.responseTime || " " }}
                </p>
              </template>
            </el-table-column>

            <el-table-column
              prop="remainingTime"
              label="剩余"
              width="100px"
              align="center"
            >
              <template #default="scope">
                <p>
                  {{ scope.row.remainingTime || " " }}
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="durationTime"
              label="持续"
              width="100px"
              align="center"
            >
              <template #default="scope">
                <p>
                  {{ scope.row.durationTime || " " }}
                </p>
              </template>
            </el-table-column>

            <el-table-column
              prop="problemDescription"
              label="问题描述"
              width="100px"
              align="center"
            />

            <el-table-column
              prop="urgencyType"
              :filters="[
                { text: 1, value: 1 },
                { text: 2, value: 2 },
                { text: 3, value: 3 },
                { text: 4, value: 4 },
                { text: 5, value: 5 },
              ]"
              class="type"
              class-name="jinji"
              :filter-method="filterTagUrgency"
              :label="urgency()"
              width="80px"
              align="center"
            />

            <el-table-column
              prop="workOrderType"
              :filters="[
                { text: '优化操作', value: 0 },
                { text: '设备故障', value: 1 },
                { text: '预测性维护', value: 2 },
              ]"
              class-name="jinji"
              :filter-method="filterTagWork_order"
              :label="work_order()"
              width="80px"
              align="center"
            >
              <template #default="scope">
                <div v-show="scope.row.workOrderType == '0'">优化操作</div>
                <div v-show="scope.row.workOrderType == '1'">设备故障</div>
                <div v-show="scope.row.workOrderType == '2'">预测性维护</div>
              </template>
            </el-table-column>

            <el-table-column
              prop="influenceType"
              label="影响范围"
              :filters="[
                { text: '能效', value: 0 },
                { text: '舒适', value: 1 },
                { text: '安全', value: 2 },
                { text: '所有', value: 3 },
              ]"
              :filter-method="filterTagInfluenceType"
              width="90px"
              align="center"
            >
              <template #default="scope">
                <div v-show="scope.row.influenceType == '0'">能效</div>
                <div v-show="scope.row.influenceType == '1'">舒适</div>
                <div v-show="scope.row.influenceType == '2'">安全</div>
              </template>
            </el-table-column>

            <el-table-column
              prop="riskType"
              label="风险"
              :filters="[
                { text: '高', value: 0 },
                { text: '中', value: 1 },
                { text: '低', value: 2 },
              ]"
              :filter-method="filterTagRiskType"
              width="70px"
              align="center"
            >
              <template #default="scope">
                <div v-show="scope.row.riskType == '0'">高</div>
                <div v-show="scope.row.riskType == '1'">中</div>
                <div v-show="scope.row.riskType == '2'">低</div>
              </template>
            </el-table-column>

            <el-table-column
              prop="involveEquipmentSystem"
              :filters="[
                { text: '制冷机', value: 0 },
                { text: '冷冻泵', value: 1 },
                { text: '冷却泵', value: 2 },
                { text: '冷却塔', value: 3 },
                { text: 'BA系统', value: 4 },
                { text: '热水崩', value: 5 },
              ]"
              :filter-method="filterTagInvolveEquipmentSystem"
              :label="equipment()"
              width="130px"
              align="center"
            />

            <el-table-column
              prop="operationalOrder"
              label="操作指令"
              width="250px"
              align="center"
            />

            <el-table-column
              prop="messageType"
              label="执行情况"
              :filters="[
                { text: '未读', value: 0 },
                { text: '已阅', value: 1 },
                { text: '成功执行', value: 2 },
                { text: '因故不执行', value: 3 },
                { text: '无理由不执行(超时关闭)', value: 4 },
              ]"
              :filter-method="filterTagMessageType"
              width="110px"
              align="center"
            >
              <template v-slot="scope">
                <el-button round size="small" @click="handleClick(scope.row)">{{
                  typemsg(scope.row.messageType)
                }}</el-button>
                <!-- <el-badge v-else  :is-dot="scope.row.messageType==0?false:true" :style="{color:scope.row.messageType==0? '#e60000':'#080000'}" class="item">
                  {{ scope.row.executiveCondition }}
                </el-badge> -->
              </template>
            </el-table-column>

            <el-table-column
              prop="executiveName"
              :label="personnel()"
              width="90px"
              align="center"
            >
            </el-table-column>

            <el-table-column
              prop="remark"
              label="备注"
              width="90px"
              align="center"
            />
          </el-table>
        </div>
        <!--分页-->
        <div class="page">
          <el-pagination
            v-model:currentPage="currentPage"
            layout="prev, pager, next, jumper"
            :hide-on-single-page="false"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!--详情弹出框-->
    <div>
      <el-dialog v-model="dialogVisible" title="工单编号" width="50%">
        <el-divider class="line" />
        <p class="number">{{ form.data.workOrderNo }}</p>
        <el-form>
          <div class="detail">
            <div>
              <div class="timetrwo">
                <p>剩余时间</p>
                <p class="time">
                  {{ form.data.remainingTime }}
                </p>
              </div>

              <div class="timer">
                <p>触发时间</p>
                <p class="time">
                  {{ form.data.triggeringTime }}
                </p>
              </div>

              <div class="timer">
                <p>预期完成时间</p>
                <p class="time">
                  {{ form.data.expectedCompletionTime }}
                </p>
              </div>
            </div>

            <div class="question">
              <div>
                <el-form-item label="问题描述">
                  <el-input
                    v-model="form.data.problemDescription"
                    disabled
                    input-style="height:50px"
                    type="textarea"
                  />
                </el-form-item>
              </div>

              <div class="center">
                <el-form-item label="可能原因">
                  <el-input
                    v-model="form.data.possibleCause"
                    disabled
                    input-style="height:60px"
                    type="textarea"
                  />
                </el-form-item>
              </div>

              <div class="center">
                <el-form-item label="操作指令">
                  <el-input
                    v-model="form.data.operationalOrder"
                    disabled
                    input-style="height:120px"
                    type="textarea"
                  />
                </el-form-item>
              </div>

              <div class="center">
                <el-form-item label="友情提示">
                  <el-input
                    v-model="form.data.friendlyReminder"
                    disabled
                    input-style="height:60px"
                    type="textarea"
                  />
                </el-form-item>
              </div>
            </div>

            <div class="right">
              <div>
                <el-form-item label="已达级别">
                  <el-input
                    v-model="form.data.executiveName"
                    disabled
                    class="label"
                    input-style="height:30px;width:250px"
                  />
                </el-form-item>
              </div>

              <div class="detail">
                <el-form-item label="工单反馈">
                  <el-select v-model="select" style="width: 250px">
                    <el-option
                      v-for="item in seList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </div>

              <div >
                <el-form-item label="无法执行">
                  <el-input
                    v-model="form.data.cannotExecute"
                    placeholder="无法执行理由陈述"
                    input-style="height:92px;width:250px"
                    type="textarea"
                  />
                </el-form-item>
                <el-button size="small" class="commit" @click="commit(3)"
                  >确认提交</el-button
                >
              </div>

              <div class="success">
                <el-form-item label="成功执行">
                  <el-input
                    v-model="form.data.successfulExecution"
                    placeholder="执行过程陈述"
                    input-style="height:92px;width:250px"
                    type="textarea"
                  />
                </el-form-item>
                <el-button size="small" class="commit" @click="commit(2)"
                  >确认提交</el-button
                >
              </div>
            </div>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import pubsub from "pubsub-js";
import isBetween from "dayjs/plugin/isBetween";
import {
  WorkOrder,
  updateWorkOrder,
  WorkOrderId,
  getCountOrder,
} from "@/api/model/end";
import { putwordmsg } from "@/api/model/login";
import { WorkOrderTime } from "@/api/model/end";

import FileSaver from "file-saver";
import * as XLSX from "xlsx/dist/xlsx.mini.min.js";
import dayjs from "dayjs";
dayjs.extend(isBetween);

const disabledDate = (time) => {
  return time.getTime() > Date.now();
};
const value = ref("");
const value1 = ref("");
const value2 = ref("");
const counts = reactive({ data: {} });
watch(
  () => value.value,
  () => {
    console.log(value.value);
    if (value.value !== "") {
      tt.value = tables.value.filter((i) => i.influenceType == value.value);
    } else {
      tt.value = tables.value;
    }
  }
);
const select = ref(0);

const currentPage = ref(1);
const total = ref(0);
const dialogVisible = ref(false);

// const pageSize = ref(100)
const tt = ref([]);
const tables = ref([]);

let form = reactive({
  data: {},
});
const formatDate = (date) => {
  var y = date.getFullYear();  
  var m = date.getMonth() + 1;  
  m = m < 10 ? '0' + m : m;  
  var d = date.getDate();  
  d = d < 10 ? ('0' + d) : d;  
  return y + '-' + m + '-' + d;  
}

const dateCreateTimeHandle = (e) => {
  console.log(e[0],e[1],"时间对象");
  if (e) {
    // const data = tt.value.filter((item) =>
    //   dayjs(item.createTime).isBetween(e[0], e[1], "day", "[]")
    // );
    // tt.value = data;
    WorkOrderTime([formatDate(e[0]),formatDate(e[1])]).then(res=>{
      tt.value = res.data.data
    })
  } else {
    getWorkOrders();
  }
};

const options1 = reactive([
  {
    label: "所有",
    value: "",
  },
  {
    label: "能效",
    value: 0,
  },
  {
    label: "舒适",
    value: 1,
  },
  {
    label: "安全",
    value: 2,
  },
]);

const options2 = reactive([
  {
    label: "一分钟",
    value: 0,
  },
  {
    label: "五分钟",
    value: 1,
  },
  {
    label: "一小时",
    value: 2,
  },
  {
    label: "一天",
    value: 3,
  },
  {
    label: "一月",
    value: 4,
  },
]);

const seList = reactive([
  {
    label: "设备正常",
    value: 0,
  },
  {
    label: "设备损坏",
    value: 1,
  },
  {
    label: "设备异常",
    value: 2,
  },
  {
    label: "其他",
    value: 3,
  },
]);
//表头下拉选项框

const filterTagInfluenceType = (value, row) => {
  return row.influenceType == value;
};

// const filterTagExecutiveName = (value, row) => {
//   return row.executiveName == value;
// };
const filterTagRiskType = (value, row) => {
  return row.riskType == value;
};

const filterTagMessageType = (value, row) => {
  return row.messageType == value;
};
const filterTagInvolveEquipmentSystem = (value, row) => {
  return row.involveEquipmentSystem == row.involveEquipmentSystem;
};
const filterTagUrgency = (value, row) => {
  return row.urgencyType == value;
};
const filterTagWork_order = (value, row) => {
  return row.workOrderType == value;
};

//设置全选框隐藏
const cellClass = (row) => {
  if (row.columnIndex === 0) {
    return "disabledCheck";
  }
};
const typemsg = (e) => {
  if (e == "0") {
    return "未读";
  } else if (e == "1") {
    return "已阅";
  } else if (e == "2") {
    return "成功执行";
  } else if (e == "3") {
    return "因故不执行";
  } else if (e == "4") {
    return "无理由不执行";
  }
};

// 表格斑马条纹
const tableRowClassName = ({ row, rowIndex }) => {
  // console.log('表格内容',row);
  row;
  if (rowIndex % 2 == 0) {
    return "warning-row";
  } else {
    return "success-row";
  }
};

function exportExcel() {
  //需给表格定义一个id或者类名
  console.log("1111111111", XLSX);
  let wb = XLSX.utils.table_to_book(document.querySelector("#table"));
  console.log("222");
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      "111.xlsx"
    ); //***是自己导出文件时的命名，随意
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;
}

// 判断上一条是否是未读状态
const wdtype = async () => {
  if (currentPage.value != 1) {
    tt.value.forEach((msg) => {
      if (Number(msg.messageType) < 2) {
        tijiao({
          id: msg.id,
          messageType: 4,
          createTime: msg.createTime,
          openTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        });
      }
    });
    return false;
  }
  tt.value.forEach((msg, idx) => {
    if (idx != 0) {
      if (msg.messageType == 0 || msg.messageType == 1) {
        tijiao({
          id: msg.id,
          messageType: 4,
          createTime: msg.createTime,
          openTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        });
      }
    }
  });
  // let i = -1;
  // console.log(tt.value, 661);
  // tt.value.forEach((msg) => {
  //   if (Number(msg.messageType) < 2) {
  //     i = 0;
  //     console.log(msg, 667);
  //   }
  //   if (i == 0) {
  //     if (Number(msg.messageType) < 2) console.log("无理由不执行", msg);
  //     msg.messageType = 4;
  //     tijiao({ id: msg.id, messageType: 4 });
  //   }
  //   console.log(i);
  // });
};
const tijiao = (msg) => {
  putwordmsg(msg);
  // put;
};
//确认提交功能
const commit = async (i) => {
  if (form.data.messageType == "0" || form.data.messageType == "1") {
    const { data } = await updateWorkOrder({
      id: form.data.id,
      messageType: i,
      createTime: form.data.createTime,
      actualFinishTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      openTime: form.data.openTime,
      cannotExecute: form.data.cannotExecute,
      successfulExecution: form.data.successfulExecution,
      feedbackType: select.value,
    });
    if (data.code !== 200) ElMessage.error(data.msg);
    getWorkOrders();
  } else {
    ElMessage.error("该类型不可操作");
  }
  dialogVisible.value = false;
};

//分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getWorkOrders();
  wdtype();
};

//点击成功按钮弹出对话框
const handleClick = async (e) => {
  dialogVisible.value = true;
  if (e.messageType == "0") {
    await putwordmsg({
      createTime: e.createTime,
      id: e.id,
      messageType: "1",
      openTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    });
    getWorkOrders();
    getCountOrders();
  }
  const { data } = await WorkOrderId(e.id);
  form.data = e;
  select.value = Number(data.data[0].feedbackType);
};

//表头文字换行
const urgency = () => {
  return `紧急\n类别`;
};

const work_order = () => {
  return `工单\n类别`;
};

const equipment = () => {
  return `涉及\n设备/系统`;
};

const personnel = () => {
  return `执行\n人员姓名`;
};

onMounted(() => {
  getWorkOrders();
  getCountOrders();
  pubsub.subscribe("refList", () => {
    getWorkOrders();
  });
});
// 获取工单统计信息
const getCountOrders = async () => {
  let { data } = await getCountOrder();
  console.log("获取工单统计信息", data);
  counts.data = { ...data.data };
};
// 获取工单列表
const getWorkOrders = async (createTime = "") => {
  let { data } = await WorkOrder({ page: currentPage.value, createTime });
  console.log("获取工单列表", data);
  if (data.code == 200) {
    tables.value = data.data.list;
    tt.value = data.data.list;
    total.value = data.data.total;
    wdtype();
  }
};
</script>

<style scoped lang='less'>
:deep(.jinji) {
  .cell {
    position: relative;

    span {
      position: absolute;
      right: 9px;
      bottom: 0;
    }
  }
}

.main {
  height: 100%;
  background-color: #eaf2fa;
  overflow: hidden;
}

.top {
  margin-left: 30px;
  margin-top: 5px;
}

.card {
  width: 100%;
  // height: 80vh;
  min-height: 780px;
  margin-top: 15px;
}

.card :deep(.el-card__body) {
  padding: 0 !important;
}

.search {
  display: flex;
  margin-top: 20px;
  margin-right: 20px;
  .itemsli {
    margin-right: 99px;
    line-height: 32px;
    font-size: 14px;
    .lis {
      font-weight: 800;
    }
  }
}

/deep/.warning-row {
  background: #fff;
}
/deep/.success-row {
  background: #f5f7fa;
}
.btn {
  margin-left: 10px;
  width: 110px;
  background-color: #92a6ce;
  color: white;
}

.el-table {
  margin-top: 10px;
  padding: 0;
}

.el-table__header tr,
.el-table__header th {
  padding: 0;
  height: 32px;
}

.el-table :deep(.disabledCheck) .cell .el-checkbox__inner {
  display: none !important;
}

.el-table :deep(.disabledCheck) > div {
  white-space: normal !important;
  line-height: 15px;
}

.el-table :deep(.disabledCheck) .cell::before {
  content: "收到确认";
}

:deep(.el-table th.el-table__cell) > .cell {
  white-space: pre;
}

.page {
  width: 100%;
  height: 3.125rem;
  margin-top: 10px;
  padding: 10px 0;
  .el-pagination {
    margin-left: 70%;
  }
}

:deep(.el-dialog__title) {
  color: #7b6ea5;
  letter-spacing: 1px;
}

.number {
  color: #636ea6;
  font-weight: bold;
  position: absolute;
  left: 110px;
  top: 25px;
}

.detail {
  display: flex;
}

.time {
  font-size: 20px;
  color: #6b8cd4;
  margin-top: 10px;
}

.timer {
  margin-top: 40px;
}

.timetrwo {
  margin-top: 30px;
}

.question {
  margin-left: 30px;
}

.center {
  margin-top: 20px;
}

.cause {
  overflow: hidden;
}

.right {
  margin-left: 30px;
}

.commit {
  height: 30px;
  width: 65px;
  position: relative;
  top: -80px;
  left: -5px;
  background-color: #8faadc;
  color: white;
}

.success {
  margin-top: 20px;
}

.line {
  position: absolute;
  top: 40px;
  left: 0px;
}

.type {
  font-size: 20px;
}

.cell {
  cursor: pointer;
  color: #606266;
}

.cell:hover {
  color: rgb(77, 98, 165);
}
</style>